[BITS 16]
[CPU 286]

global _cfopen
global _cfclose
global _cfread

%ifndef BCC
[SEGMENT _TEXT class=CODE]
%else
[SECTION .text]
%endif


; int cfopen(const char* filename, HANDLE* h)

; Function  3Dh   Open A File
;                 Open disk file with handle
; entry   AH      3Dh
;         AL      access code byte
;                         000     read only
;                         001     write only
;                         010     read/write
;                 3-7     reserved, should be set to zero
;         DS:DX   address of ASCIIZ pathname string
; return  CF set on error
;         AX      error code (01h, 02h, 03h, 04h, 05h, 0Ch)
;         AX      16 bit file handle
_cfopen:
  mov bx,sp
  mov dx,[ss:bx+2]
  mov di,[ss:bx+4]

  mov ax, 0x3D00
  int 21h
  jnc .ok
  neg ax
ret
.ok:
  mov [di], ax
  xor ax,ax
ret

; int cfclose(HANDLE handle)
;
; Function  3Eh   Close A File Handle
;                 Close a file and release handle for reuse
; entry   AH      3Eh
;         BX      file handle
; return  flag CF 0       successful close
;                 1       error
;         AX      error code if error (06h)
_cfclose:
  mov si,sp
  mov bx,[ss:si+2]
  mov ax, 0x3E00
  int 21h
  jnc .ok
  neg ax
ret
.ok:
  xor ax,ax
ret


; int cfread(void far* dst, uint16_t _size, HANDLE handle)

; Function  3Fh   Read From A File Or Device
;                 Read from file with handle
; entry   AH      3Fh
;         BX      file handle
;         CX      number of bytes to read
;         DS:DX   address of buffer
; return  flag CF 0       successful read
;                 1       error
;         AX      0       pointer was already at end of file
;                         or number of bytes read
;                         or error code (05h, 06h)
; note 1) This function attempts to transfer the number of bytes specified in CX
;         to a buffer location. It is not guaranteed that all bytes will be read
;         If AX < CX a partial record was read.
_cfread:
  mov si,sp
  mov ax,[ss:si+2]
  mov dx,[ss:si+4]
  mov cx,[ss:si+6]
  mov bx,[ss:si+8]
push ds
  mov ds,ax
  mov ax, 0x3F00
  int 21h
pop ds
  jnc .ok
  neg ax
ret
.ok:
  xor ax,ax
ret



